﻿(function () {
  'use strict';
  var controllerId = 'editproject';
  angular.module('ng4model').controller(controllerId, ['common', '$http', '$scope', '$location', '$routeParams', 'currents', 'datacontext', editproject]);

  function editproject(common, $http, $scope, $location, $routeParams, currents, datacontext) {
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);
    // store forwarded parameters
    var projectId = $routeParams.id;

    // View Model
    var vm = this;
    vm.title = 'Edit Project';
    vm.projectToEdit = {};
    vm.isValid = true;
    vm.validationSummary = '';
    activate();

    function activate() {
      var promises = [getProject()];
      common.activateController(promises, controllerId)
          .then(function () { log('Activated Projects View'); });
    }

    function getProject() {
      return datacontext.getProject(projectId).then(function (data) {
        currents.project = data;
        return vm.projectToEdit = data;
      });
    }

    // Handler
    $scope.cancel = function () {
      $location.url("/project/" + projectId);
    };

    $scope.editProject = function () {
      if ($scope.hasValidator) {
        $scope.validate(function (isvalid, errorMap) {
          if (isvalid) {
            // if is valid at client save to server
            $http.post('/Project/EditProject', JSON.stringify(vm.projectToEdit))
            .success(function (data, status) {
              $location.url("/project/" + projectId);
            })
            .error(function (data, status) {
              if (status == 400) {
                vm.isValid = false;
                vm.validationSummary = data;
              }
            });
          } else {
            vm.isValid = false;
            vm.validationSummary = errorMap;
          }
        });
      }
    };

  }
})();